<?php

namespace app\controllers;

use Yii;
use yii\rest\Controller;
use yii\web\Response;
use app\models\ActionRecord;
date_default_timezone_set("PRC");

class BaseController extends Controller
{
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['corsFilter'] = [
            'class' => 'yii\filters\Cors',
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 86400,
                'Access-Control-Expose-Headers' => [],
            ],
        ];
        return $behaviors;
    }

    public function init()
    {
        parent::init();
        Yii::$app->user->enableSession = false;
    }

    public function beforeAction($action)
    {
      parent::beforeAction($action);
      $authorization = Yii::$app->request->post('authorization', 0);
      Yii::$app->response->format = Response::FORMAT_JSON;
      if ($action->controller->id == 'img' && $action->id == 'upload-img') {
        return true;
      }

      $post = Yii::$app->request->post();
      $action_record = new ActionRecord();
      $action_record->admin_id = $action->controller->id == 'admin' ? (string)Yii::$app->user->id : (isset($post['openid']) ? $post['openid'] : '');
      $action_record->ip = Yii::$app->request->userIP;
      $action_record->controller_id = $action->controller->id;
      $action_record->action_id = $action->id;
      $action_record->post_data = json_encode($post);
      $action_record->created_at = time();
      $action_record->save();
      return true;
    }
}
